package com.qf.controller;

import com.qf.constatns.AuthConstatns;
import com.qf.feign.api.UserService;
import com.qf.utils.GsonUtils;
import com.qf.vo.Customer;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthBaiduRequest;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@RestController
@RequestMapping("/oauth")
@Slf4j
public class RestAuthController {

    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public void renderAuth(HttpServletResponse response) throws IOException {
        log.debug("用户选择了第三方的登录，引导到百度认证的页面");

        // 1.获取应用的信息
        AuthRequest authRequest = getAuthRequest();

        // 2.引导百度认证的页面
        response.sendRedirect(authRequest.authorize(AuthStateUtils.createState()));
    }

    @RequestMapping("/callback")
    public void login(AuthCallback callback, HttpSession session,HttpServletResponse response) throws IOException {
        log.debug("百度认证成功返回了code:" + callback.getCode());
        AuthRequest authRequest = getAuthRequest();

        // 1.根据Code获取AccessToken
        AuthResponse login = authRequest.login(callback);

        // 2.判断是否授权成功
        if (login.ok()) {
            // 认证授权成功
            AuthUser authUser = (AuthUser) login.getData(); // 获取用户信息

            log.debug("username:{}", authUser.getUsername());
//            log.debug("getUuid:{}", authUser.getUuid());
//            log.debug("getEmail:{}", authUser.getEmail());
//            log.debug("getAvatar:{}", authUser.getAvatar());
            // 需要考虑的用户是否是第一次使用第三方登录
            String uuid = authUser.getUuid();
            Customer customer = userService.getUserByOauthId(uuid);
            if (customer == null) {
                // 说明第一次使用第三方登录，需要做一个注册成功
                customer = new Customer();
                customer.setUsername(authUser.getUsername());
                customer.setOauthId(authUser.getUuid());
                userService.addUser(customer);
            }

            // 把当前登录的用户放入到session中
            session.setAttribute(AuthConstatns.AUTH_SESSION,customer);

            // 合并购物车

//            return "认证成功:" + GsonUtils.toJSON(authUser);
            response.sendRedirect("http://localhost/home");
        } else {
            // 认证授权失败
//            return "认证授权失败";
            response.sendRedirect("http://localhost/toLogin?msg=认证失败");
        }
    }

    private AuthRequest getAuthRequest() {
        return new AuthBaiduRequest(AuthConfig.builder()
                .clientId("kZvn2YFKthKPYtm0u2AHipqS")
                .clientSecret("VK02UIS8N8vQfo1nBLAp5RYEtbDI85NK")
                .redirectUri("http://localhost/auth/oauth/callback")
                .build());
    }
}